package com.clwl.supervise.superviseapp.service.base;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.beans.certificaReview.CertificaReviewSearchParams;
import com.clwl.supervise.superviseapp.entity.base.*;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.risk.JgSentiment;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.entity.vo.JgClassifySpscVo;
import com.clwl.supervise.superviseapp.mapper.base.*;
import com.clwl.supervise.superviseapp.mapper.risk.JgPointDistanceMapper;
import com.clwl.supervise.superviseapp.mapper.risk.JgSentimentMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BaseDataService {

    @Resource
    private JgProcessCodeMapper jgProcessCodeMapper;

    @Resource
    private JgGridMapper jgGridMapper;

    @Resource
    private TsUserMapper userMapper;

    @Resource
    private JgBusinessFormatMapper jgBusinessFormatMapper;


    @Resource
    private JgDocTemplateMapper jgDocTemplateMapper;

    @Resource
    private TcCompanyMapper companyMapper;

    @Resource
    private AdsTsYgsbhgxxMapper adsTsYgsbhgxxMapper;

    @Resource
    private JgDsjMapper jgDsjMapper;


    @Resource
    private AdsDataSourceService adsDataSourceService;
    @Resource
    private TsDeptMapper tsDeptMapper;
    @Resource
    private JgPointDistanceMapper jgPointDistanceMapper;
    @Resource
    private JgSentimentMapper jgSentimentMapper;
    @Resource
    private JgClassifySpscCompMapper jgClassifySpscCompMapper;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private JgClassifySpscMapper classifySpscMapper;

    /**
     * 获取环节列表
     *
     * @return
     */
    public List<JgProcessCode> selectProcessCodeList(String typeWhite) {
        QueryWrapper<JgProcessCode> processCodeQueryWrapper = new QueryWrapper<>();
        TsUser userLoginInfo = UserHelper.getUserInfo();
        String businessFormatRange = userLoginInfo.getBusinessFormatRange();
        String[] rangeArray = businessFormatRange.split(",");
        List<String> rangeList = Arrays.asList(rangeArray);
        processCodeQueryWrapper.in("BUSINESS_FORMAT_RANGE", rangeList);
        processCodeQueryWrapper.orderByAsc("SORT");
        if (StringUtils.isNotEmpty(typeWhite)) {
            List<String> codeList = Arrays.asList(typeWhite.split(","));
            processCodeQueryWrapper.in("CODE", codeList);
        }
        return jgProcessCodeMapper.selectList(processCodeQueryWrapper);
    }


    /**
     * 通过监管环节获取业态列表
     *
     * @param processId 环节ID
     * @return
     */
    public List<Map<String, Object>> getBusinessFormatList(String processId, String code, String parentId) {
        List processList = null;
        List parentList = null;
        List codeList = null;
        if (StringUtils.isNotEmpty(processId)) {
            String[] processIdArr = processId.split(",");
            processList = Arrays.asList(processIdArr);
        }
        if (StringUtils.isNotEmpty(parentId)) {
            String[] parentIdArr = parentId.split(",");
            parentList = Arrays.asList(parentIdArr);
        }
        if (StringUtils.isNotEmpty(code)) {
            String[] codeArr = code.split(",");
            codeList = Arrays.asList(codeArr);
        }
        return jgBusinessFormatMapper.selectBusinessFormatList(processList, codeList, parentList);
    }

    /**
     * 获取监管人员列表
     * 当前人员所在的网络负责人合并后列表
     * 当前人员所在部门所有人员
     *
     * @return
     */
    public List<TsUser> getSupervisePersonList() {
        Long userId = UserHelper.getUserId();
        Set<Long> usersSet = new LinkedHashSet<>();
        //获取所在网格所有人员
        List<JgGrid> gridList = jgGridMapper.selectGridListByUserId(userId);
        for (JgGrid jgGrid : gridList) {
            usersSet.add(jgGrid.getGridPerson1Id());
            usersSet.add(jgGrid.getGridPerson2Id());
        }
        //获取当前人员所有在部门所有人员
        TsUser user = userMapper.selectById(userId);
        List<TsUser> userList = userMapper.selectByDeptId(user.getDeptId());
        if (usersSet.size() > 0) {
            List<TsUser> userList2 = userMapper.selectByIds(usersSet);
            userList.addAll(userList2);
        }
        ArrayList<TsUser> userListAll = new ArrayList<>();
        ArrayList<Long> userListIdAll = new ArrayList<>();
        for (TsUser tsUser : userList) {
            if (!userListIdAll.contains(tsUser.getId())) {
                userListIdAll.add(tsUser.getId());
                userListAll.add(tsUser);
            }
        }
        List<TsUser> resultUserlist = new ArrayList<>();
        for (TsUser tsUser : userListAll) {
            tsUser.setValue(tsUser.getId());
            tsUser.setText(tsUser.getName());// + (user.getEnforcementNo() == null ? "" : "/" + user.getEnforcementNo()));
            if (StringUtils.equals("0", tsUser.getDisabledStatus())) {
                resultUserlist.add(tsUser);
            }
        }
        return resultUserlist;
    }

    /**
     * 获取文书模板列表
     */
    public List<JgDocTemplate> getDocTemplateList() {
        QueryWrapper<JgDocTemplate> docTemplateQueryWrapper = new QueryWrapper<>();
        return jgDocTemplateMapper.selectList(docTemplateQueryWrapper);
    }

    /**
     * 根据企业id，通过规则进行排序，获取路线规划
     *
     * @param companyIds 企业id
     * @param type       1-按时限，2-按受处罚、历史检查发现问题，3-按风险高低
     * @param checktype  检查类型；1-日常检查；2-双随机检查；3-飞行检查；4-体系检查
     */
    public List<Map<String, Object>> getRoutePlanList(String companyIds, String type, String checktype, String pointLat, String pointLng) {
        String[] companyArr = companyIds.split(",");
        List<Map<String, Object>> companyList = companyMapper.getRoutePlanList(Arrays.asList(companyArr), type, checktype);
        List<Map<String, Object>> companySortList = new ArrayList<>();
        if (StringUtils.isBlank(type)) {
            sortCompany(pointLat, pointLng, companyList, companySortList);
        } else {
            companySortList = companyList;
        }
        return companySortList;
    }

    /**
     * 级联排序规划路线  计算和上一个点的最近的距离 通过此距离排序
     *
     * @param pointLat
     * @param pointLng
     * @param companyList
     * @param companySortList
     */
    private static void sortCompany(String pointLat, String pointLng, List<Map<String, Object>> companyList, List<Map<String, Object>> companySortList) {
        List<Map<String, Object>> sortList = new ArrayList<>();
        log.info("companyList:{}", companyList);
        for (Map<String, Object> companyMap : companyList) {
            String lngLat = companyMap.get("LNG_LAT") == null ? null : companyMap.get("LNG_LAT").toString();
            if (lngLat == null) {
                continue;
            }
            double distance = haversineDist(pointLat, pointLng, lngLat.split(",")[1], lngLat.split(",")[0]);
            Map<String, Object> sortMap = new HashMap<>();
            sortMap.put("id", companyMap.get("ID"));
            sortMap.put("distance", distance);
            sortList.add(sortMap);
        }
        if (sortList.size() == 0) {
            return;
        }
        List<Map<String, Object>> sortReadyList = sortList.stream().sorted((map1, map2) -> Double.compare(
                Double.parseDouble(map1.get("distance").toString()),
                Double.parseDouble(map2.get("distance").toString())
        )).collect(Collectors.toList());
        log.info("sortReadyList:{}", sortReadyList);
        Map<String, Object> sortReadMap = sortReadyList.get(0);
        Iterator<Map<String, Object>> companyListo = companyList.iterator();
        while (companyListo.hasNext()) {
            Map<String, Object> map = companyListo.next();
            if (map.get("ID").toString().equals(sortReadMap.get("id").toString())) {
                companySortList.add(map);
                pointLat = map.get("LNG_LAT") == null ? null : map.get("LNG_LAT").toString().split(",")[1];
                pointLng = map.get("LNG_LAT") == null ? null : map.get("LNG_LAT").toString().split(",")[0];
                //删除companyListo中当前元素
                companyListo.remove();
            }
        }
        sortCompany(pointLat, pointLng, companyList, companySortList);
    }

    public static double haversineDist(String lat1S, String long1S, String lat2S, String long2S) {
        final int R = 6371; // Earth's radius in kilometers
        double lat1 = StringUtils.isNotEmpty(lat1S) ? Double.parseDouble(lat1S) : 0;
        double long1 = StringUtils.isNotEmpty(long1S) ? Double.parseDouble(long1S) : 0;
        double lat2 = StringUtils.isNotEmpty(lat2S) ? Double.parseDouble(lat2S) : 0;
        double long2 = StringUtils.isNotEmpty(long2S) ? Double.parseDouble(long2S) : 0;
        // convert the latitudes and longitudes from decimal degrees to radians
        double dLat = Math.toRadians(lat2 - lat1);
        double dLong = Math.toRadians(long2 - long1);

        // calculate the a value
        double a = Math.pow(Math.sin(dLat / 2), 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2))
                * Math.pow(Math.sin(dLong / 2), 2);

        // calculate the c value
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        // calculate the actual distance
        double distance = R * c;

        return distance;
    }

    /**
     * 获取任务数量统计
     *
     * @return
     */
    public Map<String, Object> getTaskCountStatistics(String type) {
        Map<String, Object> params = new HashMap<>();
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.put("userId", UserHelper.getUserId());
        params.put("dataRange", dataRange);
        params.put("deptId", UserHelper.getUserInfo().getDeptId());
        params.put("businessFormatRange", UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.put("dataDeptId", dataDeptEntity.getId());
        } else {
            params.put("dataDeptId", UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("1") >= 0) {
            //包含经营
            params.put("isJy", "1");
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.put("isSc", "1");
        } else {
            params.put("isSc", "0");
        }

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.put("processList", processList);

        params.put("currentYear", DateUtil.year(new Date()));
        Map<String, Object> result = new HashMap<>();
        result.put("SHU", "-");
        switch (type) {
            case "richang":
                try {
                    return this.getDailyTaskCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询日常检查统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "shuangsuiji":
                try {
                    return this.getDoubleTaskCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询双随机检查统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "zhenggai":
                try {
                    return this.getRectificationCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询整改统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "chaoqi":
                try {
                    return this.getOverdueCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询日常检查超期统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "tixi":
                try {
                    return this.getSystemTaskCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询体系检查统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "zhenghou":
                try {
                    return this.getSyndromeReviewCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询证后统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "feixing":
                try {
                    return this.getFlightTaskCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询飞行检查统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "pingfen":
                try {
                    if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("1") >= 0) {
                        //包含经营
                        return this.getScoreFutureCountStatistics(params);
                    } else {
                        result.put("SHU", "0");
                        return result;
                    }
                } catch (Exception e) {
                    log.error("首页查询评分统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "pingji":
                try {
                    if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("1") >= 0) {
                        //包含经营
                        return this.getGradeFutureCountStatistics(params);
                    } else {
                        result.put("SHU", "0");
                        return result;
                    }
                } catch (Exception e) {
                    log.error("首页查询评级统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            case "chufajuedingshu":
                try {
                    return new HashMap<>();//this.getPunishCountStatistics(params);
                } catch (Exception e) {
                    log.error("首页查询处罚统计信息错误登陆人:{},----报错信息:{}", UserHelper.getUserId(), e.getMessage());
                    return result;
                }
            default:
                return result;
        }
    }


    public Map<String, Object> getOverdueCountStatistics(Map<String, Object> params) {
        return companyMapper.selectOverdueCountStatistics(params);
    }

    public Map<String, Object> getPunishCountStatistics(Map<String, Object> params) {
        return companyMapper.selectPunishCountStatistics(params);
    }

    public Map<String, Object> getGradeFutureCountStatistics(Map<String, Object> params) {
        return companyMapper.selectGradeCountStatistics(params);
    }

    public Map<String, Object> getScoreFutureCountStatistics(Map<String, Object> params) {
        return companyMapper.selectScoreCountStatistics(params);
    }

    public Map<String, Object> getSyndromeReviewCountStatistics(Map<String, Object> map) {
        CertificaReviewSearchParams params = new CertificaReviewSearchParams();

        String dataRange = UserHelper.getUserInfo().getDataRange();
        TsDept dept = tsDeptMapper.selectById(UserHelper.getUserInfo().getDeptId());

        if (!UserHelper.getUserId().equals("0") && !dataRange.equals("0")) {
            if (dataRange.equals("1")) {
                params.setDeptQuId(dept.getParentId());
            } else if (dept.getLvl() == 2 && StringUtils.equals("1", dept.getParentId() + "")) {
                params.setDeptQuId(UserHelper.getUserInfo().getDeptId());
            } else {
                params.setDeptId(UserHelper.getUserInfo().getDeptId());
            }
        }
        Map<String, Object> resultMap = companyMapper.selectSyndromeRevieCountStatistics(params);
        return resultMap;
    }

    public Map<String, Object> getFlightTaskCountStatistics(Map<String, Object> map) {
        CommonSearchEntity params = new CommonSearchEntity();
        params.setCreatorId(UserHelper.getUserId());
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }
        return companyMapper.selectFlightTaskCountStatistics(params);
    }

    public Map<String, Object> getSystemTaskCountStatistics(Map<String, Object> map) {
        CommonSearchEntity params = new CommonSearchEntity();
        params.setCreatorId(UserHelper.getUserId());
        String dataRange = UserHelper.getUserInfo().getDataRange();
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(dataRange);
        params.setDeptId(UserHelper.getUserInfo().getDeptId());
        params.setBusinessFormatRange(UserHelper.getUserInfo().getBusinessFormatRange());
        String deptType = "3";
        if ("0".equals(dataRange)) {
            deptType = "0";
        } else if ("1".equals(dataRange)) {
            deptType = "1";
        } else if ("2".equals(dataRange)) {
            deptType = "2";
        } else if ("3".equals(dataRange)) {
            deptType = "2";
        }
        TsDept dataDeptEntity = tsDeptMapper.getDataParentDeptId(UserHelper.getUserInfo().getDeptId(), deptType);
        if (dataDeptEntity != null) {
            params.setDataDeptId(dataDeptEntity.getId());
        } else {
            params.setDataDeptId(UserHelper.getUserInfo().getDeptId());
        }
        if (UserHelper.getUserInfo().getBusinessFormatRange().indexOf("2") >= 0 || UserHelper.getUserInfo().getBusinessFormatRange().indexOf("3") >= 0) {
            params.setIsSc("1");
        } else {
            params.setIsSc("0");
        }

        return companyMapper.selectSystemTaskCountStatistics(params);
    }

    public Map<String, Object> getRectificationCountStatistics(Map<String, Object> params) {
        return companyMapper.selectRectificationCountStatistics(params);
    }

    public Map<String, Object> getDoubleTaskCountStatistics(Map<String, Object> params) {
        return companyMapper.selectDoubleTaskCountStatistics(params);
    }

    public Map<String, Object> getDailyTaskCountStatistics(Map<String, Object> params) {
        return companyMapper.selectDailyTaskCountStatistics(params);
    }


    /**
     * 获取文书模板详情
     *
     * @param templateId 模板ID
     */
    public String getDocTemplateInfo(Long templateId) {
        JgDocTemplate template = jgDocTemplateMapper.selectById(templateId);
        return template.getTemplateContentOriginal();
    }

    /**
     * 修改主体坐标信息
     */
    public void editCompanyPoint(Long companyId, String lat, String lng) {
        TcCompany company = companyMapper.selectById(companyId);
        company.setLngLat(lng + "," + lat);
        companyMapper.updateById(company);
    }

    /**
     * 企业列严
     *
     * @return
     */
    public Map<String, Object> getLieYanByCreditCode(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        return jgDsjMapper.getLieYanByCreditCode(company.getCreditCode());
    }

    ;

    public int getLieYanByCreditCodeCount(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        return jgDsjMapper.getLieYanByCreditCodeCount(company.getCreditCode());
    }

    ;

    /**
     * 企业列异
     *
     * @return
     */
    public Map<String, Object> getLieYiByCreditCode(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        return jgDsjMapper.getLieYiByCreditCode(company.getCreditCode());
    }

    ;

    public int getLieYiByCreditCodeCount(Long companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        return jgDsjMapper.getLieYiByCreditCodeCount(company.getCreditCode());
    }

    ;

    /**
     * 企业抽样不合格
     *
     * @return
     */
    @DS("ads")
    public Map<String, Object> getChouyangByLicense(String license, String creditCode) {
        return adsTsYgsbhgxxMapper.getChouyangByLicense(license, creditCode);
    }


    @DS("ads")
    public int getChouyangByLicenseCount(String license, String creditCode) {
        return adsTsYgsbhgxxMapper.getChouyangByLicenseCount(license, creditCode);
    }

    ;

    /**
     * 许可证即将过期
     *
     * @return
     */
    public Map<String, Object> getLicenseByCompanyId(Long companyId) {
        return jgDsjMapper.getLicenseByCompanyId(companyId);
    }


    public int getLicenseByCompanyIdCount(Long companyId) {
        return jgDsjMapper.getLicenseByCompanyIdCount(companyId);
    }


    @Transactional(rollbackFor = Exception.class)
    public void pointConversion() {
        Page<Map<String, Object>> iPage = Page.of(0, 170000);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        List<TcCompany> companyList = companyMapper.selectEntityList(iPage);
        log.info("企业数：{}", companyList.size());
        AtomicInteger num = new AtomicInteger(0);
        for (TcCompany tcCompany : companyList) {
            log.info("tcCompany:{}", tcCompany.getPzLngLat());
            if (tcCompany.getPzLngLat() != null) {
                try {
                    // String[] lntlat = tcCompany.getPzLngLat().split(",");
                    //Double lnt = Double.parseDouble(lntlat[0]);
                    //Double lat = Double.parseDouble(lntlat[1]);
                    //请求高德地图坐标转换接口	be0b4ba83d5ce1b753f3a9559bc23f52
                    String key1 = "be0b4ba83d5ce1b753f3a9559bc23f52"; //王
                    String key2 = "805b320e37829fab47601cbdde73c7c0"; //我
                    URL url = new URL("https://restapi.amap.com/v3/assistant/coordinate/convert?locations=" + tcCompany.getPzLngLat() + "&coordsys=gps&key=" + key1);
                    // 打开和URL之间的连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    // 设置通用的请求属性
                    connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setUseCaches(false);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    // 建立实际的连接
                    connection.connect();
                    // 获取所有响应头字段
                    // Map<String, List<String>> headers = connection.getHeaderFields();
                    // 遍历所有的响应头字段
             /*   for (String key : headers.keySet()) {
                    System.err.println(key + "--->" + headers.get(key));
                }*/
                    // 定义 BufferedReader输入流来读取URL的响应
                    //in = null;
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(connection.getInputStream(), "UTF-8"));

                    String result = "";
                    String getLine;
                    while ((getLine = in.readLine()) != null) {
                        result += getLine;
                    }
                    in.close();
                    log.info("result:{}", result);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if ("1".equals(resultJson.getString("status"))) {
                        tcCompany.setLngLat(resultJson.getString("locations"));
                        companyMapper.updateById(tcCompany);
                    }

                    // double[] bd09 = Coordtransform.redressGps(lnt, lat);
                    //String newLngLat = bd09[0] + "," + bd09[1];

                    log.info("企业{},id{}坐标转换完成,已完成{}", tcCompany.getCompanyName(), tcCompany.getId(), num.addAndGet(1));
                } catch (Exception e) {
                    log.error("企业{},id{}坐标转换失败", tcCompany.getCompanyName(), tcCompany.getId());
                }
            }

        }
    }

    /**
     * 获取今年抽检不通过的数量
     *
     * @return
     */
    @DS("ads")
    public Map<String, Object> getChouyangByThisYear() {
        return adsTsYgsbhgxxMapper.selectCountMap();
    }


    public TcCompany getCompanyInfo(Long companyId) {
        return companyMapper.selectById(companyId);
    }

    public Map<String, String> riskInfo(Long companyId) {
        Map<String, String> riskMap = new HashMap<String, String>();
        //主体资格
        Map<String, Object> licenseMap = getLicenseByCompanyId(companyId);
        if (licenseMap != null) {
            String yxqz = licenseMap.get("YXQZ").toString().replaceAll("年", "-").replaceAll("月", "-").replaceAll("日", "-");
            //与当前提起做对比
            long day = DateUtil.betweenDay(new Date(), DateUtil.parse(yxqz, "yyyy-MM-dd"), true);
            if (day < 60) {
                riskMap.put("subjectQualification", "存在许可证异常");
            } else {
                riskMap.put("subjectQualification", "0");
            }
        } else {
            riskMap.put("subjectQualification", "0");
        }
        //主体标注
        TcCompany company = this.getCompanyInfo(companyId);
        if (company.getLngLat() == null) {
            riskMap.put("bodyCallouts", "存在异常");
        } else {
            riskMap.put("bodyCallouts", "0");
        }
        //抽检信息
        if (adsDataSourceService.getChouyangByLicenseCount(company.getLicense(), company.getCreditCode()) > 0) {
            riskMap.put("foodSafe", "存在抽样检测不合格");
        } else {
            riskMap.put("foodSafe", "0");
        }

        //处罚信息
        riskMap.put("punishInfo", "0");

        //投诉举报
        riskMap.put("complaintsReport", "0");

        //包保督导
        riskMap.put("packageSupervision", adsDataSourceService.getBaobaoRisk(company.getLicense()) + "");

        //舆情风险
        QueryWrapper<JgSentiment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sup_process", company.getSupProcess());
        if (StringUtils.equalsAny(company.getSupProcess(), "tssc", "spsc")) {
            QueryWrapper<JgClassifySpscComp> classifySpscCompQueryWrapper = new QueryWrapper<>();
            classifySpscCompQueryWrapper.eq("COMPANY_ID", companyId);
            List<JgClassifySpscComp> classifySpscCompsList = jgClassifySpscCompMapper.selectList(classifySpscCompQueryWrapper);
            //用stream生成JgClassifySpscComp的主键id的list
            List<Long> classifyIdList = classifySpscCompsList.stream().map(JgClassifySpscComp::getClassifySpsc1Id).collect(Collectors.toList());
            queryWrapper.in("sup_process_two", classifyIdList);
        } else {
            queryWrapper.eq("sup_process_two", company.getCompanyTypeId());
        }
        Long jgSentimentCount = jgSentimentMapper.selectCount(queryWrapper);
        riskMap.put("opinionRisk", jgSentimentCount + "");


        //信用风险
    /*    if (baseDataService.getLieYanByCreditCodeCount(companyId) > 0) {
        	riskMap.put("creditRisk","已列入严重违法失信名单等");
        }else if(baseDataService.getLieYiByCreditCodeCount(companyId) > 0) {
        	riskMap.put("creditRisk","已列入异常经营名录等");
        }else{
        	riskMap.put("creditRisk","0");
        };*/


        //其他风险
        //riskMap.put("otherRisk","0");
        return riskMap;
    }

    /**
     * 获取检查范围距离
     *
     * @param companyId
     * @return
     */
    public JgPointDistance getCheckDistance(String companyId) {
        TcCompany company = companyMapper.selectById(companyId);
        QueryWrapper<JgPointDistance> pointDistanceQueryWrapper = new QueryWrapper<>();
        pointDistanceQueryWrapper.eq("delete_flag", "0");
        pointDistanceQueryWrapper.eq("SUP_PROCESS", company.getSupProcess());
        return jgPointDistanceMapper.selectOne(pointDistanceQueryWrapper);
    }

    /**
     * 根居CODE获取对象
     */
    public JgProcessCode findJgProcessCodeByCode(String code) {
        return jgProcessCodeMapper.selectByCode(code);
    }

    /**
     * 查列表
     */
    public List<JgClassifySpscVo> findClassifySpscList(JgClassifySpsc jgClassifySpsc) {
        List<JgClassifySpscVo> list = null;
        try {
            list = classifySpscMapper.findList(jgClassifySpsc);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 查询企业舆情
     *
     * @param company
     */
    public List<JgSentiment> selectSentimentList(TcCompany company) {
        QueryWrapper<JgSentiment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sup_process", company.getSupProcess());
        if (StringUtils.equalsAny(company.getSupProcess(), "tssc", "spsc")) {
            QueryWrapper<JgClassifySpscComp> classifySpscCompQueryWrapper = new QueryWrapper<>();
            classifySpscCompQueryWrapper.eq("COMPANY_ID", company.getId());
            List<JgClassifySpscComp> classifySpscCompsList = jgClassifySpscCompMapper.selectList(classifySpscCompQueryWrapper);
            //用stream生成JgClassifySpscComp的主键id的list
            List<Long> classifyIdList = classifySpscCompsList.stream().map(JgClassifySpscComp::getClassifySpsc1Id).collect(Collectors.toList());
            queryWrapper.in("sup_process_two", classifyIdList);
        } else {
            queryWrapper.eq("sup_process_two", company.getCompanyTypeId());
        }
        return jgSentimentMapper.selectList(queryWrapper);
    }

    public List<AdsBaobShareSupTaskDetailEntity> getBaobaoRisk(TcCompany company) {
        return adsDataSourceService.selectBaobaoRiskContent(company);
    }
}
